// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
jQuery.noConflict();
$(document).ready(function() {   
    //   Combo dependiente de 1 a 1 (tipo de institucion cultural sobre instituciones culturales)
    $('select#cultural_heritage_cultural_heritage_typeCulturalInstitution').change(function() {
        if ( ($('select#cultural_heritage_cultural_heritage_typeCulturalInstitution').val() != '')) {
            $.ajax({
                url: '/cultural_heritage/cultural_heritages/change_cultural_institutions/' + $(this).val(),
                type: 'GET',
                cache: false,
                complete: function(html) {
                    $("#cultu_insti_type").html(html.responseText);
                }
            })
        }
        else
        {
            $("#cultu_insti_type select").find("option:gt(0)").remove()
        }
    });
    // Combo dependiente de 1 a 1 (dpto x provincia)
    $('select#request_and_complaint_complaint_department').change(function() {
        if ( ($('select#request_and_complaint_complaint_department').val() != '')) {
            $.ajax({
                url: '/request_and_complaint/complaints/change_provinces/' + $(this).val(),
                type: 'GET',
                cache: false,
                complete: function(html) {
                    $("#provinces").html(html.responseText);
                }
            })
        }
        else
        {
            $("#provinces select").find("option:gt(0)").remove()
        }
    });
    // Combo dependiente de 1 a 1 (provincia x distrito)
    $('select#request_and_complaint_complaint_province').live('change',function() {
        if ( ($('select#request_and_complaint_complaint_province').val() != '')) {
            $.ajax({
                url: '/request_and_complaint/complaints/change_districts/' + $(this).val(),
                type: 'GET',
                cache: false,
                complete: function(html) {
                    $("#districts").html(html.responseText);
                }
            })
        }
        else
        {
            $("#districts select").find("option:gt(0)").remove()
        }
    });

    // Combo dependiente de 1 a 1 (dpto x provincia)
    $('select#request_and_complaint_registration_request_department').change(function() {
        if ( ($('select#request_and_complaint_registration_request_department').val() != '')) {
            $.ajax({
                url: '/request_and_complaint/registration_requests/change_provinces/' + $(this).val(),
                type: 'GET',
                cache: false,
                complete: function(html) {
                    $("#provinces").html(html.responseText);
                }
            })
        }
        else
        {
            $("#provinces select").find("option:gt(0)").remove()
        }
    });

    $('select#request_and_complaint_registration_request_province').live('change',function() {
        if ( ($('select#request_and_complaint_registration_request_province').val() != '')) {
            $.ajax({
                url: '/request_and_complaint/registration_requests/change_districts/' + $(this).val(),
                type: 'GET',
                cache: false,
                complete: function(html) {
                    $("#districts").html(html.responseText);
                }
            })
        }
        else
        {
            $("#districts select").find("option:gt(0)").remove()
        }
    });

    // Combo dependiente de 1 a 1 (departament x provincia)
    $('select#cultural_heritage_cultural_institution_department').live('change',function() {
        if ( ($('select#cultural_heritage_cultural_institution_department').val() != '')) {
            $.ajax({
                url: '/cultural_heritage/cultural_institutions/change_provinces/' + $(this).val(),
                type: 'GET',
                cache: false,
                complete: function(html) {
                    $("#provinces").html(html.responseText);
                }
            })
        }
        else
        {
            $("#provinces select").find("option:gt(0)").remove()
        }
    });

    // Combo dependiente de 1 a 1 (provincia x distrito)
    $('select#cultural_heritage_cultural_institution_province').live('change',function() {
        if ( ($('select#cultural_heritage_cultural_institution_province').val() != '')) {
            $.ajax({
                url: '/cultural_heritage/cultural_institutions/change_districts/' + $(this).val(),
                type: 'GET',
                cache: false,
                complete: function(html) {
                    $("#districts").html(html.responseText);
                }
            })
        }
        else
        {
            $("#districts select").find("option:gt(0)").remove()
        }
    });

    //   Combo dependiente de 1 a 1 (sub grupo sobre periodos)
    $('select#cultural_heritage_cultural_heritage_subGroup').change(function() {
        if ( ($('select#cultural_heritage_cultural_heritage_subGroup').val() != '')) {
            $.ajax({
                url: '/cultural_heritage/cultural_heritages/change_periods/' + $(this).val(),
                type: 'GET',
                cache: false,
                complete: function(html) {
                    $("#period").html(html.responseText);
                }
            })
        }
        else
        {
            $("#period select").find("option:gt(0)").remove()
        }
    });

    $('select#cultural_heritage_cultural_heritage_period').live('change',function() {
        if ( ($('select#cultural_heritage_cultural_heritage_period').val() != '')) {
            $.ajax({
                url: '/cultural_heritage/cultural_heritages/change_cultures/' + $(this).val(),
                type: 'GET',
                cache: false,
                complete: function(html) {
                    $("#culture").html(html.responseText);
                }
            })
        }
        else
        {
            $("#culture select").find("option:gt(0)").remove();            
        }
    });
    // Combo dependiente de 2 a 1 (grupo y sub grupo sobre tipologia)
    $('select#cultural_heritage_cultural_heritage_subGroup').change(function() {
        if ( ($('select#cultural_heritage_cultural_heritage_group').val() != '') && ($('select#cultural_heritage_cultural_heritage_subGroup').val() != '')) {
            $.ajax({
                url: '/cultural_heritage/cultural_heritages/change_tipologies/'+$('input[type="hidden"]#heritage_group').val()+'/'+$('select#cultural_heritage_cultural_heritage_subGroup').val(),
                type: 'GET',
                cache: false,
                complete: function(html) {
                    //El resultado lo reemplazamos en el div q tiene el select de paises
                    $("#tipology").html(html.responseText);
                }
            })
        }
        else
        {
            $("#tipology select").find("option:gt(0)").remove()
        }
    });
    // Combo dependiente de 1 a 1 (dpto x provincia) en busqueda
    $('select#search_department').change(function() {
        if ( ($('select#search_department').val() != '')) {
            $.ajax({
                url: '/cultural_heritage/cultural_institutions/change_provinces_search/' + $(this).val(),
                type: 'GET',
                cache: false,
                complete: function(html) {
                    $("#provinces_search").html(html.responseText);
                }
            })
        }
        else
        {
            $("#provinces_search select").find("option:gt(0)").remove()
        }
    });
    // Muestra divs dependiendo de la seleccion del combo
    $('select#cultural_heritage_cultural_heritage_group').change(function() {        
        switch ($(this).val()) {
            case "":
                // para el prmt, igual a nivel de vista se debe setear como non visible x defecto
                $("#weight").hide();
                $("#shape").hide();
                $("#foundInId").hide();
                break;
            case "1":
                //es mueble
                $("#weight").show();
                $("#shape").show();
                $("#foundInId").show();
                break;
            case "2":
                //es inmueble
                $("#weight").hide();
                $("#shape").hide();
                $("#foundInId").hide();
                break;
        }
    });
    $('select#cultural_heritage_cultural_heritage_subGroup').live('change',function() {
        switch ($(this).val()) {
            case "":
                // para el prmt, igual a nivel de vista se debe setear como non visible x defecto
                //$("#cultura").hide();
                $("#technique").hide();
                break;
            case "1":
                //es arqueologico
                //$("#cultura").show();
                $("#technique").hide();
                break;
            case "2":
                //es historico
                //$("#cultura").hide();
                break;
        }
    });
    //    $('select#cultural_heritage_cultural_heritage_tipology').change(function() {
    $('select#cultural_heritage_cultural_heritage_tipology').live('change',function() {
        switch ($(this).val()) {
            case "":
                // para el prmt, igual a nivel de vista se debe setear como non visible x defecto
                $("#technique").hide();
                break;
            case "1":
                //es arqueologico
                $("#technique").hide();
                break;
            case "2":
                //es historico
                $("#technique").hide();
                break;
            case "3":
                //es historico
                $("#technique").hide();
                break;
            case "4":
                //es historico
                $("#technique").hide();
                break;
            case "5":
                //es historico
                $("#technique").hide();
                break;
            case "6":
                //es historico
                $("#technique").hide();
                break;
            case "7":
                //es historico
                $("#technique").hide();
                break;
            case "8":
                //es historico
                $("#technique").hide();
                break;
            case "9":
                //es historico
                $("#technique").hide();
                break;
            case "10":
                //es historico
                $("#technique").hide();
                break;
            case "11":
                //es historico
                $("#technique").hide();
                break;
            case "12":
                //es historico
                $("#technique").show();
                break;
            case "13":
                //es historico
                $("#technique").hide();
                break;
            case "14":
                //es historico
                $("#technique").hide();
                break;
            case "15":
                //es historico
                $("#technique").hide();
                break;
            case "16":
                //es historico
                $("#technique").hide();
                break;
            case "17":
                //es historico
                $("#technique").hide();
                break;
        }
    });
    // Busqueda de incidentes
    $('form#cultural_heritage_incidences_form_search').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#incidences_table").html(response.responseText);
                $( ".paginated_table" ).tablePagination({});
                $(".sorted_table").tablesorter();
            }

        });
        return false;
    });
    // Busqueda de periodos
    $('form#periods_form_search').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#periods_table").html(response.responseText);
                $( ".paginated_table" ).tablePagination({});
                $(".sorted_table").tablesorter();
            }

        });
        return false;
    });
    //Busqueda de denuncias
    $('form#complaints_form_search').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#complaints_table").html(response.responseText);
                $( ".paginated_table" ).tablePagination({});
                $(".sorted_table").tablesorter();
            }

        });
        return false;
    });
    //Busqueda de Solicitudes de Inscripcion
    $('form#registration_requests_form_search').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#registration_requests_table").html(response.responseText);
                $( ".paginated_table" ).tablePagination({});
                $(".sorted_table").tablesorter();
            }

        });
        return false;
    });

    //Busqueda de Solicitudes de Preregistro
    $('form#pre_register_requests_form_search').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#pre_register_requests_table").html(response.responseText);
                $( ".paginated_table" ).tablePagination({});
                $(".sorted_table").tablesorter();
            }

        });
        return false;
    });
    //Busqueda de culturas
    $('form#cultures_form_search').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#cultures_table").html(response.responseText);
                $( ".paginated_table" ).tablePagination({});
                $(".sorted_table").tablesorter();
            }

        });
        return false;
    });


    // busqueda de insitituciones culturales
    $('form#cultural_heritage_cultural_institutions_form_search').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#cultural_heritage_cultural_institutions_table").html(response.responseText);
                $( ".paginated_table" ).tablePagination({});
                $(".sorted_table").tablesorter();
            }

        });
        return false;
    });

    // busqueda de patromonio cultural mueble
    $('form#cultural_heritage_form_search').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#cultural_heritage_table").html(response.responseText);
                $( ".paginated_table" ).tablePagination({});
                $(".sorted_table").tablesorter();
            }

        });
        return false;
    });

    $('form#cultural_heritage_parts_form_search').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#cultural_heritage_partes_table").html(response.responseText);
                $( ".paginated_table" ).tablePagination({});
                $(".sorted_table").tablesorter();
            }

        });
        return false;
    });

    $('form#cultural_heritage_properties_form_search').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#cultural_heritage_properties_table").html(response.responseText);
                $( ".paginated_table" ).tablePagination({});
                $(".sorted_table").tablesorter();
            }

        });
        return false;
    });

    //    $('form#cultural_heritage_form_search_map').submit(function() {
    //        $.ajax({
    //            url: $(this).attr('action'),
    //            type: 'POST',
    //            data: $(this).serialize(),
    //            complete: function(response) {
    //                $("#cultural_heritage_map").html(response.responseText);
    //            }
    //
    //        });
    //        return false;
    //    });
    //
    //    $('form#cultural_heritage_properties_form_search_map').submit(function() {
    //        $.ajax({
    //            url: $(this).attr('action'),
    //            type: 'POST',
    //            data: $(this).serialize(),
    //            complete: function(response) {
    //                $("#cultural_heritage_properties_map").html(response.responseText);
    //            }
    //
    //        });
    //        return false;
    //    });

    $('form#cultural_heritage_cultural_institutions_form_search_map').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#cultural_heritage_cultural_institutions_map").html(response.responseText);
            }

        });
        return false;
    });
    // Busqueda de usuarios
    $('form#users_form_search').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#users_table").html(response.responseText);
                $( ".paginated_table" ).tablePagination({});
                $(".sorted_table").tablesorter();
            }

        });
        return false;
    });

    // Busqueda de colecciones
    $('form#collections_form_search').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#collections_table").html(response.responseText);
                $( ".paginated_table" ).tablePagination({});
                $(".sorted_table").tablesorter();
            }

        });
        return false;
    });

    // Busqueda de colecciones
    $('form#collections_form_search').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#collections_table").html(response.responseText);
                $( ".paginated_table" ).tablePagination({});
                $(".sorted_table").tablesorter();
            }

        });
        return false;
    });

    // busqueda de cuidado y mantenimiento
    $('form#care_and_maintenances_form_search').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#care_and_maintenances_table").html(response.responseText);
                $( ".paginated_table" ).tablePagination({});
                $(".sorted_table").tablesorter();
            }

        });
        return false;
    });

    

    // Busqueda de patrimonios para trasladar
    $('form#cultural_heritage_form_transfer_search').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#cultural_heritage_transfer_form_table").html(response.responseText);
                $( ".paginated_table" ).tablePagination({});
                $(".sorted_table").tablesorter();
            }

        });
        return false;
    });

    //Busqueda de traslados
    $('form#transfers_form_search').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#transfers_table").html(response.responseText);
                $( ".paginated_table" ).tablePagination({});
                $(".sorted_table").tablesorter();
            }

        });
        return false;
    });

    //Busqueda de traslados
    $('form#transfers_form_search').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#transfers_table").html(response.responseText);
                $( ".paginated_table" ).tablePagination({});
                $(".sorted_table").tablesorter();
            }

        });
        return false;
    });

    //FIN  DE BÚSQUEDAS

    $('form#cultural_heritage_properties_assing_form_search').submit(function() {
        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            complete: function(response) {
                $("#cultural_heritage_assing_table").html(response.responseText);
                $( ".paginated_table" ).tablePagination({});
                $(".sorted_table").tablesorter();
            }

        });
        return false;
    });


    $('table#list_to_select a.js_link_cultural_heritage').live('click', function(e) {
        e.preventDefault();
        var cultural_heritage_id = $(this).attr('cultural-heritage-id');
        if ($('table#list_selected tbody tr td a[cultural-heritage-id="'+cultural_heritage_id.toString()+'"]').length == 0) {
            var td_code = $(this).parent().parent().find('td.national_registration_code').first().clone();
            var td_name = $(this).parent().parent().find('td.name').first().clone();

            //Clona el tag <a /> desde el que se llama y llena los atributos
            var a_unselect = $(this).clone().attr({
                'class':'js_unlink_cultural_heritage',
                'title':'Desasociar'
            }).text('');
            //Crea tag img para mostrar imagen de desasociar
            var img_unselect = $('<img/>').attr({
                'title':'Desasociar',
                'src':'/images/navi/0045-badge-circle-direction-left-16-ns.png',
                'alt':'Desasociar'
            });

            //incrusta el tag <img /> dentro del <a />
            a_unselect.append($(img_unselect));

            var input_field = $('<input/>').attr({
                'type': 'hidden',
                'name': 'cultural_heritage_selected[]',
                'value': cultural_heritage_id
            });
                        
            var td_unselect = $('<td/>').append($(a_unselect), $(input_field));

            //			td_unselect.append($(input_field));
            var new_tr = $('<tr/>');
            $(new_tr).append($(td_code));
            $(new_tr).append($(td_name));
            $(new_tr).append($(td_unselect));
            $('table#list_selected tbody').append($(new_tr));
        }
    });

    $('table#list_selected a.js_unlink_cultural_heritage').live('click', function(e) {
        e.preventDefault();
        $(this).parent().parent().remove();
    });

    $('form#form_select').submit(function() {
        if ($('table#list_selected tbody tr td a[cultural-heritage-id]').length == 0) {
            alert('Selecciona al menos 1 basura!');
            return false;
        } else {
            return true;
        }
    });

    $("#red").treeview({
        animated: "fast",
        collapsed: true,
        unique: true,
        persist: "cookie",
        toggle: function() {
            window.console && console.log("%o was toggled", this);
        }
    });

    $('td a.js_delete_pre_pregister').click(function(e) {
        e.preventDefault();
        $('span#pre_register_attrs_'+$(this).attr('pre_register_id')).remove();
        $(this).parent().parent().remove();
    });

    //Aqui tenemos el codigo para la fecha
    if ($('span.js_change_field_send_date').length) {
        //Si salimos del foco, es decir dejamos de escribir en el campo, debemos mandar la llamada ajax para cambiar el campo en base de datos
        $('input#cultural_heritage_pre_register_request_send_date').blur(function() {
            $.ajax({
                url:'change_attribute',
                cache:false,
                type:'POST',
                data:'field=send_date&new_value="'+encodeURIComponent($(this).val())+'"',
                success: function() { /* Si la llamada ajax se ejecuto, volvemos a ocultar el input y mostramos el label de nuevo actualizado con el nuevo valor */
                    $('input#cultural_heritage_pre_register_request_send_date').hide();
                    $('span.js_change_field_send_date').html($('input#cultural_heritage_pre_register_request_send_date').val()).show();
                }
            });
        });

        //Si hacemos click en el label, debemos ocultarlo y mostrar el input para modificarlo
        $('span.js_change_field_send_date').click(function(e) {
            e.preventDefault();
            $(this).hide();
            $(this).parent().find('input#cultural_heritage_pre_register_request_send_date').show().focus();
        });
    }

    //Lo mismo que arriba
    if ($('span.js_change_field_state').length) {

        $('select#cultural_heritage_pre_register_request_state').blur(function() {
            $.ajax({
                url:'change_attribute',
                cache:false,
                type:'POST',
                data:'field=state&new_value='+encodeURIComponent($(this).val()),
                success: function() {
                    $('select#cultural_heritage_pre_register_request_state').hide();
                    $('span.js_change_field_state').html($('select#cultural_heritage_pre_register_request_state option:selected').text()).show();
                }
            });
        });

        $('span.js_change_field_state').click(function(e) {
            e.preventDefault();
            $(this).hide();
            $(this).parent().find('select#cultural_heritage_pre_register_request_state').show().focus();
        });
    }

    //Lo mismo que arriba
    if ($('span.js_change_field_description').length) {

        $('textarea#cultural_heritage_pre_register_request_description').blur(function() {
            $.ajax({
                url:'change_attribute',
                cache:false,
                type:'POST',
                data:'field=description&new_value='+encodeURIComponent($(this).val()),
                success: function() {
                    $('textarea#cultural_heritage_pre_register_request_description').hide();
                    $('span.js_change_field_description').html($('textarea#cultural_heritage_pre_register_request_description').val()).show();
                }
            });
        });

        $('span.js_change_field_description').click(function(e) {
            e.preventDefault();
            $(this).hide();
            $(this).parent().find('textarea#cultural_heritage_pre_register_request_description').show().focus();
        });
    }



    //Validaciones

    function vacio(q) {
        for ( i = 0; i < q.length; i++ ) {
            if ( q.charAt(i) != " " ) {
                return true;
            }
        }
        return false;
    }

    function isNumber(str)
    {
        if (typeof(str)=='undefined')
        {
            return false;
        }
        var expr1 = /^[\+\-]?[0-9]+(\.[0-9]{0,})?$/;
        var expr2 = /^[\+\-]?(\.[0-9]{0,})?$/;
        if (!expr1.test(str)){
            if (!expr2.test(str)){
                return false;
            }
        }
        return true;
    }   

    $('div#complaints_table table.paginated_table a.asign_complaint').live("click", function(e) {
        e.preventDefault();
        var value_select = 0;
        if ($("select#complaint_responsible").val()) {
            value_select = $("select#complaint_responsible").val();
        }
        window.location = $(this).attr('href').toString().replace("replace_user_id",value_select);
    });

    $('div#registration_requests_table table.paginated_table a.asign_registration_request').live("click", function(e) {
        e.preventDefault();
        var value_select = 0;
        if ($("select#registration_request_responsible").val()) {
            value_select = $("select#registration_request_responsible").val();
        }
        window.location = $(this).attr('href').toString().replace("replace_user_id",value_select);
    });


    $('table.paginated_table a.approve_pre_registers').live("click", function(e) {
        e.preventDefault();
        var value_select = 0;
        if ($("input#search_input").val()) {
            value_select = $("input#search_input").val();
        }
        window.location = $(this).attr('href').toString().replace("replace_user_id",encodeURIComponent(value_select));
    });


    $('table.paginated_table a.approve_pre_registers_properties').live("click", function(e) {
        e.preventDefault();
        var value_select = 0;
        if ($("input#search_input").val()) {
            value_select = $("input#search_input").val();
        }
        window.location = $(this).attr('href').toString().replace("replace_user_id",encodeURIComponent(value_select));
    });

    $('#notice').live('click', function( e ) {
       $(this).slideUp('slow');
    });

});
